package io.renren.modules.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.web.entity.UserEntity;
import io.renren.modules.web.form.RegisterForm;
import io.renren.modules.web.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @Author jiajia
 * @Date 2019/12/18 14:45
 **/
@RestController
@RequestMapping("admin/user")
@Api("用户管理")
public class WebUserController {
    @Autowired
    private UserService userService;

    @PostMapping("add")
    @ApiOperation("添加用户")
    @RequiresPermissions("admin:user:save")
    public R register(@RequestBody RegisterForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        UserEntity user = new UserEntity();
        user.setMobile(form.getMobile());
        user.setUsername(form.getUsername());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setCreateTime(new Date());
        user.setType(form.getType());
        userService.save(user);

        return R.ok();
    }

    /**
     * 用户列表
     */
    @GetMapping("/list")
    //@RequiresPermissions("admin:user:list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
    })
    public R list(@RequestParam Map<String, Object> params){

            PageUtils page = userService.queryPage(params);

            return R.ok().put("page", page);
    }


    /**
     * 删除用户
     */
    @PostMapping("del")
    public R deleteUser(@RequestBody Long[] ids ){
        userService.deleteByIds(ids);
        return new R();
    }

    @GetMapping("info/{userId}")
   // @RequiresPermissions("admin:user:info")
    @ApiOperation("获取用户名")
    public R info(@PathVariable("userId")  Long userId){
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.select("username");
        UserEntity user = userService.getOne(wrapper);
        return new R().put("user",user);
    }

}
